package com.demo.example.goods.web;

import com.demo.example.goods.service.GoodsService;
import com.demo.example.dto.OrderDTO;
import com.demo.example.dto.GoodsDTO;
import com.demo.example.service.GoodsCompositeService;
import com.demo.example.goods.dao.GoodsRepository;
import com.demo.example.goods.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by azhai on 2017/4/20.
 */
@RestController
@RequestMapping("/api/goods")
public class GoodsResource implements GoodsCompositeService {

    @PostConstruct
    public void init() {
        if (goodsRepository.count() > 0) {
            return;
        }
        Goods goods = new Goods();
        goods.setName("No.1");
        goods.setGoodsNum(110L);
        goodsRepository.save(goods);
    }

    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private GoodsService goodsService;

    @PostMapping("")
    public OrderDTO create(@RequestBody OrderDTO dto) {
        return dto;
    }

    @GetMapping("/{customerId}")
    public List<GoodsDTO> getMyGoods(@PathVariable(name = "customerId") Long customerId) {
        List<Goods> goodsList = goodsRepository.findAllByOwner(customerId);
        return goodsList.stream().map(goods -> {
            GoodsDTO dto = new GoodsDTO();
            dto.setGoodsNum(goods.getGoodsNum());
            dto.setId(goods.getId());
            dto.setLockUser(goods.getLockUser());
            dto.setName(goods.getName());
            dto.setOwner(goods.getOwner());
            return dto;
        }).collect(Collectors.toList());
    }

    @PostMapping("/lock")
    public Goods lock(@RequestBody OrderDTO dto) {
        return goodsService.lockGoods(dto);
    }
    @PostMapping("/lock2")
    public int lock2(@RequestBody OrderDTO dto) {
        return goodsService.lockGoods2(dto);
    }

    @GetMapping("")
    public List<Goods> getAll() {
        return goodsRepository.findAll();
    }

}
